import type { ShareItem } from '#/api/openapi';

import { acceptHMRUpdate, defineStore } from 'pinia';

import { formatTime } from '#/utils/time';

// 分享历史记录项
export interface ShareHistoryItem {
  id: string; // 本地生成的唯一ID
  shareCode: string; // 分享码
  shareItem: ShareItem; // 完整的分享信息
  accessTime: number; // 访问时间戳（毫秒）
  downloadCount?: number; // 本地记录的下载次数
}

interface ShareHistoryState {
  history: ShareHistoryItem[];
}

/**
 * 分享历史记录 Store
 */
export const useShareHistoryStore = defineStore('share-history', {
  state: (): ShareHistoryState => ({
    history: [],
  }),

  getters: {
    // 获取所有分享历史记录（带格式化时间）
    getAllHistory: (state): (ShareHistoryItem & { formattedTime: string })[] =>
      state.history.map((item) => ({
        ...item,
        formattedTime: formatTime(new Date(item.accessTime)),
      })),

    // 获取统计信息
    getStats: (state) => {
      const total = state.history.length;
      const totalFiles = state.history.reduce(
        (sum, item) => sum + (item.shareItem.files?.length || 0),
        0,
      );
      const totalDownloads = state.history.reduce(
        (sum, item) => sum + (item.downloadCount || 0),
        0,
      );

      return {
        total,
        totalFiles,
        totalDownloads,
      };
    },

    // 根据分享码查找
    getByShareCode:
      (state) =>
      (
        shareCode: string,
      ): (ShareHistoryItem & { formattedTime: string }) | undefined => {
        const item = state.history.find((item) => item.shareCode === shareCode);
        return item
          ? {
              ...item,
              formattedTime: formatTime(new Date(item.accessTime)),
            }
          : undefined;
      },

    // 获取最近访问的分享记录
    getRecent:
      (state) =>
      (limit = 10): (ShareHistoryItem & { formattedTime: string })[] => {
        return state.history.slice(0, limit).map((item) => ({
          ...item,
          formattedTime: formatTime(new Date(item.accessTime)),
        }));
      },

    // 检查分享码是否已存在
    hasShareCode:
      (state) =>
      (shareCode: string): boolean => {
        return state.history.some((item) => item.shareCode === shareCode);
      },
  },

  actions: {
    /**
     * 添加新的分享历史记录
     */
    addShareHistory(shareCode: string, shareItem: ShareItem) {
      // 检查是否已存在相同的分享码
      const existingIndex = this.history.findIndex(
        (item) => item.shareCode === shareCode,
      );

      const historyItem: ShareHistoryItem = {
        id: `share-${Date.now()}`,
        shareCode,
        shareItem,
        accessTime: Date.now(),
        downloadCount: 0,
      };

      if (existingIndex !== -1) {
        // 如果已存在，更新访问时间并移到最前面
        this.history.splice(existingIndex, 1);
      }

      // 添加到历史记录顶部
      this.history.unshift(historyItem);

      // 限制历史记录数量，最多保留50条
      if (this.history.length > 50) {
        this.history = this.history.slice(0, 50);
      }
    },

    /**
     * 更新分享历史记录
     */
    updateShareHistory(id: string, updates: Partial<ShareHistoryItem>) {
      const index = this.history.findIndex((item) => item.id === id);
      if (index !== -1) {
        const currentItem = this.history[index];
        if (currentItem) {
          this.history[index] = {
            ...currentItem,
            ...updates,
          };
        }
      }
    },

    /**
     * 记录文件下载
     */
    recordDownload(shareCode: string, _fileId?: number | string) {
      const item = this.history.find((item) => item.shareCode === shareCode);
      if (item) {
        item.downloadCount = (item.downloadCount || 0) + 1;
        // 更新访问时间
        item.accessTime = Date.now();

        // 将该项移到最前面
        const index = this.history.findIndex((h) => h.id === item.id);
        if (index > 0) {
          this.history.splice(index, 1);
          this.history.unshift(item);
        }
      }
    },

    /**
     * 删除分享历史记录
     */
    removeShareHistory(id: string) {
      const index = this.history.findIndex((item) => item.id === id);
      if (index !== -1) {
        this.history.splice(index, 1);
      }
    },

    /**
     * 根据分享码删除记录
     */
    removeByShareCode(shareCode: string) {
      const index = this.history.findIndex(
        (item) => item.shareCode === shareCode,
      );
      if (index !== -1) {
        this.history.splice(index, 1);
      }
    },

    /**
     * 清空所有分享历史记录
     */
    clearHistory() {
      this.history = [];
    },

    /**
     * 清理过期的分享记录
     */
    clearExpiredShares() {
      const now = new Date();
      this.history = this.history.filter((item) => {
        if (item.shareItem.expiryTime) {
          const expiryTime = new Date(item.shareItem.expiryTime);
          return expiryTime > now;
        }
        return true; // 没有过期时间的保留
      });
    },

    /**
     * 初始化示例数据（开发用）
     */
    initSampleData() {
      if (this.history.length === 0) {
        this.history = [];
      }
    },
  },

  // 持久化配置
  persist: {
    key: 'share-history',
    storage: localStorage,
    pick: ['history'], // 只持久化 history 字段
  },
});

// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
  hot.accept(acceptHMRUpdate(useShareHistoryStore, hot));
}
